<script setup lang="ts">
	import { ref, onMounted } from "vue";
	import { formRules } from "./utils/rule";
	import { FormProps } from "./utils/types";
	import ReCol from "@/components/ReCol";
  import { baseUrlApi, baseOaApi } from "@/api/utils";
  import type { UploadProps } from "element-plus";
  import { message } from "@/utils/message";
  import {
    typeSelect
  } from "@/api/projectApi";
	const props = withDefaults(defineProps<FormProps>(), {
		formInline: () => ({
			title: "",
			status: 0,
			Id: 0,
		})
	});
	const ruleFormRef = ref();
	const newFormInline = ref(props.formInline);
	function getRef() {
		return ruleFormRef.value;
	}
	defineExpose({ getRef });
  // 类型列表

  const taskTypeSelect = ref()
  const getTypeSelect = async() => {
    const res: any = await typeSelect();
    let children = []
    for (let item of res?.result) {
      if(item?.child) {
        for (let row of item?.child) {
          for (let child of row) {
            children.push(child)
          }
        }
      }
    }
    taskTypeSelect.value = [...res?.result, ...children];
  }
  const statusSelect = [
    // {id: 0, name: '未开始'},
    {id: 1, name: '进行中'},
    {id: 2, name: '已完成'},
    {id: 3, name: '已关闭'},
  ]
  const actionUrl = baseUrlApi + "/uploadFile/upload";

  const fileList = ref()
  const imgUrl = ref("");
  const handleAttachmentSuccess: UploadProps["onSuccess"] = (
    response,
    uploadFile
  ) => {
    console.log(response,fileList)
    // imgUrl.value = URL.createObjectURL(uploadFile.raw!);
    // newFormInline.value.attachment = baseOaApi + response.result.path;
    newFormInline.value.attachment = fileList.value
  };
  const beforeUpload = (file) => {
    const isContract = file.name.endsWith('.pdf') || file.name.endsWith('.doc') || file.name.endsWith('.docx'); // 检查文件类型是否为合同文件类型（例如：PDF, DOC, DOCX）
    const isLt500kb = file.size / 1024 < 500; // 检查文件大小是否小于500kb
    // if (!isContract) {
    //   message("文件格式不支持!", {
    //     type: "error"
    //   });
    //   return false; // 不允许上传非合同文件类型
    // }
    // if (!isLt500kb) {
    //   message("上传文件大小不能超过500kb!", {
    //     type: "error"
    //   });
    //   return false; // 不允许上传大于500kb的文件
    // }
    return true;
  }
  const uploadRef = ref()
  const submitUpload = () => {
    uploadRef.value!.submit()
  }
  const handlePreview = (file) => {
    let link = document.createElement("a"); //定义一个a标签
    link.download = file.name; //下载后的文件名称
    link.href = file.url; //需要生成一个 URL 来实现下载
    link.click(); //模拟在按钮上实现一次鼠标点击
    window.URL.revokeObjectURL(link.href);
  }
  onMounted(()=> {
    if(newFormInline.value.attachment && newFormInline.value.attachment.length > 0) {
      fileList.value = [{name: newFormInline.value.attachment, url: newFormInline.value.attachment}]
    }
    getTypeSelect()
  })
  const calculateWorkingHours = (s, e) => {
    const start = new Date(s);
    const end = new Date(e);
    let count = 0;
    const oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
    for (let i = start; i <= end; i.setTime(i.getTime() + oneDay)) {
      const day = i.getDay();
      if (day !== 0 && day !== 6) { // 0 = Sunday, 6 = Saturday
        count++;
      }
    }
    return count*8;
  }
  const datePickerChange = (val) => {
    if(val) {
      newFormInline.value.expectHour = calculateWorkingHours(val[0], val[1])
    }
  }
  const assignedChange = (val) => {
    if(val.length > 1) {
      newFormInline.value.hasMultiUser = 1
    } else {
      newFormInline.value.hasMultiUser = 0
    }

  }
  const defaultTime = [new Date(2000, 1, 1, 8, 30, 0), new Date(2000, 1, 1, 18, 0, 0),]
</script>

<template>
	<el-form ref="ruleFormRef" :model="newFormInline" :rules="formRules" label-width="auto">
		<el-row :gutter="30">
			<re-col :value="12" :xs="24" :sm="24">
				<el-form-item label="所属项目" prop="projectId">
					<el-select
					  v-model="newFormInline.projectId"
					  placeholder="请选择所属项目"
					  clearable
            disabled
					>
					  <el-option
					    v-for="item in newFormInline.projectSelect"
					    :key="item.projectId"
					    :label="item.projectName"
					    :value="item.projectId"
					  />
					</el-select>
				</el-form-item>
			</re-col>
      <re-col :value="12" :xs="24" :sm="24">
      	<el-form-item label="任务类型" prop="taskType">
          <el-select
            v-model="newFormInline.taskType"
            placeholder="请选择所属项目"
            clearable
            disabled
          >
            <el-option
              v-for="item in taskTypeSelect"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
      	</el-form-item>
      </re-col>

      <re-col :value="24" :xs="24" :sm="24">
      	<el-form-item label="指派用户" prop="assignedTo">
          <el-select
            v-model="newFormInline.assignedTo"
            placeholder="请选择指派用户"
            clearable
            multiple
            filterable
            @change="assignedChange"
          >
            <el-option
              v-for="item in newFormInline.userSelect"
              :key="item.userId"
              :label="item.name"
              :value="item.userId"
            />
          </el-select>
      	</el-form-item>
      </re-col>
      <re-col :value="24" :xs="24" :sm="24">
        <el-form-item label="是否多人任务" prop="hasMultiUser" required>
        	<el-radio-group v-model="newFormInline.hasMultiUser">
            <el-radio :value="0">单人</el-radio>
            <el-radio :value="1">多人</el-radio>
          </el-radio-group>
        </el-form-item>
      </re-col>
      <re-col :value="24" :xs="24" :sm="24">
      	<el-form-item label="计划日期" prop="rangePlanDate">
      		<el-date-picker
            v-model="newFormInline.rangePlanDate"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
            @change="datePickerChange"
            :default-time="defaultTime"
          />
      	</el-form-item>
      </re-col>
			<re-col :value="12" :xs="24" :sm="24">
				<el-form-item label="优先级" prop="priority">
					<el-input-number
						v-model="newFormInline.priority"
						class="!w-full"
						:min="1"
						:max="4"
						controls-position="right"
            :precision="0"
					  />
				</el-form-item>
			</re-col>
      <re-col :value="12" :xs="24" :sm="24">
      	<el-form-item label="预计小时" prop="expectHour">
      		<el-input-number
      			v-model="newFormInline.expectHour"
      			class="!w-full"
      			:min="0"
      			:max="9999"
      			controls-position="right"
            :precision="0"
            :step="8"
      		  />
      	</el-form-item>
      </re-col>


      <!-- <re-col :value="12" :xs="24" :sm="24">
      	<el-form-item label="完成比例" prop="completeRate">
      		<el-input-number
      			v-model="newFormInline.completeRate"
      			class="!w-full"
      			:min="0"
      			:max="100"
      			controls-position="right"
            :precision="0"
            :step="5"
      		  />
      	</el-form-item>
      </re-col> -->
      <re-col :value="24" :xs="24" :sm="24">
      	<el-form-item label="抄送给用户" prop="assignedExtraTo">
      		<el-select
      		  v-model="newFormInline.assignedExtraTo"
      		  placeholder="请选择抄送用户"
      		  clearable
      		  multiple
            filterable
      		>
      		  <el-option
      		    v-for="item in newFormInline.userSelect"
      		    :key="item.userId"
      		    :label="item.name"
      		    :value="item.userId"
      		  />
      		</el-select>
      	</el-form-item>
      </re-col>
      <re-col :value="24" :xs="24" :sm="24">
      	<el-form-item label="关键词" prop="keyword">
      		<el-input v-model="newFormInline.keyword" clearable placeholder="请输入关键词"  :rows="2" type="textarea"/>
      	</el-form-item>
      </re-col>
      <re-col :value="24" :xs="24" :sm="24">
      	<el-form-item label="描述" prop="description">
          <el-input v-model="newFormInline.description" clearable placeholder="请输入描述" :rows="2" type="textarea"/>
      	</el-form-item>
      </re-col>
      <!-- <re-col :value="24" :xs="24" :sm="24">
      	<el-form-item label="附件">
      		<el-upload
      		  ref="uploadRef"
      		  :action="actionUrl"
      		  :on-success="handleAttachmentSuccess"
      		  v-model:file-list="fileList"
      		  :before-upload="beforeUpload"
            :on-preview="handlePreview"
            style="width: 100%;"
            :limit="1"
            drag
      		  multiple>
      		  <el-button type="primary" link size="large" @click="submitUpload">上传附件</el-button>
      		</el-upload>
      	</el-form-item>
      </re-col> -->
		</el-row>
	</el-form>
</template>
<style scoped>
	.avatar-uploader .el-upload {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		text-align: center;
	}
</style>
